<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/10/5 0005
 * Time: 下午 4:05
 */
namespace app\api\tool;


use think\Cache;
use think\Session;

class Message
{
    /**
     * 发送短信
     * @param $mobile
     * @param string $content
     * @param string $company
     * @return mixed
     */
    public function sendMessage($mobile, $content = '', $company = '玩车头条')
    {
        $data = [];
        $data['mobile'] = $mobile;
        $data['content'] = $content;
        $data['company'] = $company;
        $result=http_request_center('api/message/send', $data);
        if($result['code']==1){
            return ['code'=>1,'msg'=>'发送成功'];
        }else{
            log_debug("发送短息失败", $mobile.'|'.$content.'|'.$result['msg']);
            return ['code'=>0,'msg'=>'发送失败'];
        }
    }

    /**
     * 获取验证码并缓存
     */
    public function getCode($mobile)
    {
        $length = config("message_code_length");
        $code = '';
        for ($i = 0; $i < $length; $i++) {
            $code .= rand(0, 9);
        }
        $result = [
            'message_code' => $code,
            'out_time' => config("message_code_valid_time") + time()
        ];
        Cache::set("message_code_" . $mobile, $code, config("message_code_valid_time"));
//        session("message_code_".$mobile,$result);
        return $result;
    }


    /**
     * 检查验证码
     * @param $code
     * @return array
     */
    public function checkCode($mobile, $code)
    {
        $result = Cache::get("message_code_" . $mobile);

        if ($result) {
            if ($result != $code) {
                return ['code' => 0, 'msg' => "验证码错误！"];
            } else
                return ['code' => 1, 'msg' => '验证成功！'];

        } else {
            return ['code' => 0, 'msg' => "验证码过期了"];
        }
    }

    /**
     * 清楚验证码
     * @param $mobile
     */
    public static function clearCode($mobile)
    {
        Cache::rm("message_code_" . $mobile);
    }

    /**
     * 发送消息验证码
     */
    public function sendRegisterCode($mobile)
    {
        //检查用户是否注册了
        $memberService = service('Member');
        if ($memberService->isRegister($mobile)) {
            return ['code' => 0, 'msg' => 'mobile_has_register'];
        }
        $result = $this->getCode($mobile);
        //检查是否过期
        $content = "尊敬的用户，你的验证码为" . $result['message_code'] . ",有效时间为10分钟,请不要泄漏你的验证码";
        $res = $this->sendMessage($mobile, $content);
        return $res;
    }

    public function sendFindPasswordCode($mobile)
    {
        //检查用户是否注册了
        $memberService = service('Member');
        if (!$memberService->isRegister($mobile)) {
            return ['code' => 0, 'msg' => 'mobile_no_register'];
        }

        $result = $this->getCode($mobile);
        //检查是否过期
        $content = "尊敬的用户，你的验证码为" . $result['message_code'] . ",有效时间为10分钟,请不要泄漏你的验证码";
        $res = $this->sendMessage($mobile, $content);
        return $res;

    }


}